package com.group.controller;

import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.base.view.BaseResult;
import com.base.view.GeneralResult;
import com.base.view.ListResult;
import com.group.model.*;
import com.group.util.NoteException;

/**
 * 新闻管理
 * 
 * @author zhaolei
 *
 */
@Controller
public class NewsController extends BaseController {

	/**
	 * 添加/修改新闻
	 * 
	 * @param news
	 * @return
	 */
	@PostMapping("/news/add")
	@ResponseBody
	@CacheEvict(value = { "queryNews", "queryNewsById" }, allEntries = true)
	public GeneralResult<News> addNews(@RequestBody News news) {
		// 增加标记
		Random r = new Random();
		int i = r.nextInt(100);
		if (i < 20) {
			news.setSpecialType(2);
		} else if (i >= 20 & i < 40) {
			news.setSpecialType(1);
		} else {
			news.setSpecialType(0);
		}

		beanDao.save(news);

		// 删除旧标签
		beanDao.quickDelete(Newstag.class, "newsId", news.getId());

		for (Tag tag : news.getTags()) {
			Newstag nt = new Newstag();
			nt.setNewsId(news.getId());
			nt.setTagId(tag.getId());
			beanDao.save(nt);
		}

		// 删除币的旧标签
		beanDao.quickDelete(TickerTag.class, "newsId", news.getId());

		// 保存币的标签
		for (TickerTag tag : news.getTickerTags()) {
			tag.setNewsId(news.getId());
			beanDao.save(tag);
		}

		return new GeneralResult<News>().setValue(news);
	}

	/**
	 * 删除新闻
	 * 
	 * @param newsId
	 * @return
	 */
	@DeleteMapping("/news/delete")
	@ResponseBody
	@CacheEvict(value = { "queryNews", "queryNewsById" }, allEntries = true)
	public BaseResult deleteNews(Long newsId) {
		beanDao.quickDelete(News.class, "id", newsId);

		return new BaseResult();
	}

	/**
	 * 查询新闻列表
	 * 
	 * @param key
	 *            关键字
	 * @param type
	 *            类型
	 * @param tagName
	 *            标签名称
	 * @param state
	 *            状态
	 * @param order
	 *            排序种类, 1 按热门
	 * @param isHot
	 *            是否热门 1 热门
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping("/news/query")
	@ResponseBody
	public ListResult<News> queryNews(String key, String type, String tagName, Integer state, Integer order, Integer isHot, Integer start, Integer limit) {
		String sort = null;
		if (order != null && 1 == order) {
			sort = "order by n1.read desc";
		}

		return new ListResult<News>().setList(newsDao.queryNews(key, type, tagName, state, sort, isHot, start, limit)).setTotal(newsDao.queryNewsCount(key, type, tagName, state, sort, isHot));
	}

	/**
	 * 根据cid查询新闻
	 * 
	 * @param cid
	 * @param type
	 *            类型
	 * @param state
	 *            状态
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping("/news/query/cid")
	@ResponseBody
	public ListResult<News> queryNewsByCid(String cid, String type, Integer state, Integer start, Integer limit) {

		return new ListResult<News>().setList(newsDao.queryNewsByCid(cid, type, state, start, limit)).setTotal(newsDao.queryNewsByCidCount(cid, type, state));
	}

	/**
	 * 更新新闻状态
	 * 
	 * @param newsId
	 * @param state
	 * @return
	 */
	@GetMapping("/news/state/update")
	@ResponseBody
	@CacheEvict(value = { "queryNews", "queryNewsById" }, allEntries = true)
	public GeneralResult<News> updateNewsState(Long newsId, Integer state) {
		synchronized (newsId) {
			News news = newsService.queryById(newsId);
			if (news == null) {
				throw new NoteException("news 不存在");
			}

			if (state == 1 && news.getBoardId() != null) {
				Topic topic = new Topic();
				topic.setNewsId(news.getId());
				topic.setBoardId(news.getBoardId());
				if (beanDao.queryOne(topic) == null) {

					topic.setNewsDesc(news.getTopicDesc());
					topic.setNewsFileId(news.getFileId());
					topic.setNewsTitle(news.getTitle());

					topic.setIsSelect(news.getTopicSelect());
					topic.setIsAnalysis(news.getTopicAnalysis());
					beanDao.save(topic);
				}
			}

			news.setCreateTime(new Date());
			news.setState(state);
			beanDao.save(news);
			return new GeneralResult<News>().setValue(news);
		}

	}

	/**
	 * 查询完整新闻
	 * 
	 * @param newsId
	 * @return
	 */
	@GetMapping("/news/query/id")
	@ResponseBody
	@CacheEvict(value = { "queryNews", "queryNewsById" }, allEntries = true)
	public GeneralResult<News> queryNewsById(Long newsId) {
		News news = newsService.queryById(newsId);

		if (news == null) {
			return null;
		}

		// 随机阅读量
		Random r = new Random();

		news.setRead(news.getRead() + r.nextInt(20) + 1);
		news.setRealRead(news.getRealRead() + 1);
		beanDao.save(news);
		news.setTags(newsDao.queryNewsTag(newsId));

		news.setRealRead(null);

		// 查询币的标签
		news.setTickerTags(beanDao.quickQueryList(TickerTag.class, "newsId", newsId));

		return new GeneralResult<News>().setValue(news);
	}

	/**
	 * 给新闻添加标签
	 * 
	 * @param newsId
	 * @param tagId
	 * @return
	 */
	@GetMapping("/news/tag/add")
	@ResponseBody
	@CacheEvict(value = { "queryNews", "queryNewsById" }, allEntries = true)
	public BaseResult addNewsTag(Long newsId, Long tagId) {
		Newstag nt = new Newstag();
		nt.setNewsId(newsId);
		nt.setTagId(tagId);

		if (beanDao.queryOne(nt) == null) {
			beanDao.save(nt);
		}

		return new BaseResult();
	}

	/**
	 * 查询用户的新闻
	 * 
	 * @param userId
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping(value = { "/back/user/news/query", "/news/user/query" })
	@ResponseBody
	public ListResult<News> queryUserNews(Long userId, Integer start, Integer limit) {
		if (userId == null) {
			throw new NoteException("userId 不能为空");
		}

		List<News> list = userDao.queryUserNews(userId, start, limit);

		return new ListResult<News>().setList(list).setTotal(userDao.queryUserNewsCount(userId));
	}

	/**
	 * 设置新闻是否为热门新闻
	 * 
	 * @param newsId
	 * @param isHot
	 * @return
	 */
	@GetMapping("/news/isHot")
	@ResponseBody
	public BaseResult setHot(Long newsId, Integer isHot) {
		News news = new News();
		news.setId(newsId);
		news.setIsHot(isHot);
		beanDao.save(news);

		return new BaseResult();
	}

}
